import asyncio
import logging
import threading
import time

from BinanceSignal.BinanceKlineFactroy import twist_klines
from BinanceSignal.BinanceSignalInitAlpha import BinanceSignalInitAlpha
from BinanceStrategy.BinanceStrategyInitAlpha import BinanceStrategyInitAlpha

logging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s',
                    level=logging.INFO)


class BinanceStrategy(BinanceStrategyInitAlpha):
    def __init__(self, UID: int, APIKey: str, SecretKey: str, symbol: str):
        super().__init__(UID, APIKey, SecretKey, symbol)
        self.logger.info("开始运行 用户ID:" + str(self.UID))
        self.task_lock = False
        # session = DbSession()
        # data = session.query(digiccy_member).filter_by(id=self.UID).first()
        # self.DMBalance = data.balance
        # self.logger.info("用户邮费: " + str(self.DMBalance))
        # session.close()

    def _profit_loss(self, pl):
        self.consume(pl)

    def execute_end(self):
        self.task_lock = False

    def _close_before(self):
        self.logger.info("停止运行")
        data = self.account(recvWindow=self.recvWindow)
        positions = data.get("positions")
        unrealizedProfit = 0
        for var in positions:
            if var.get("symbol") == self.symbol:
                unrealizedProfit += float(var.get("unrealizedProfit"))
        self.consume(unrealizedProfit)

    def consume(self, pl):
        pass
        # try:
        #     session = DbSession()
        #     pl = pl * 0.3
        #     session.query(digiccy_member).filter_by(id=self.UID).update({"balance": digiccy_member.balance - pl})
        #     data = session.query(digiccy_member).filter_by(id=self.UID).first()
        #     self.DMBalance = data.balance
        #     self.logger.info("用户邮费: " + str(self.DMBalance))
        #     session.commit()
        #     session.close()
        # except:
        #     ex_type, ex_val, ex_stack = sys.exc_info()
        #     self.logger.warning(ex_val)


class BinanceQuantify(BinanceSignalInitAlpha):
    def __init__(self, symbol):
        super().__init__(symbol)
        self.user_list = []
        self.task_list = []

    def _score_update(self, score, now_price):  # 分数(或K线)更新执行
        low_nums = [twist_klines(self.klines_1m)["low"].values[-2],
                    twist_klines(self.klines_3m)["low"].values[-2],
                    twist_klines(self.klines_5m)["low"].values[-2],
                    twist_klines(self.klines_15m)["low"].values[-2],
                    twist_klines(self.klines_30m)["low"].values[-2],
                    twist_klines(self.klines_1h)["low"].values[-2]]

        high_nums = [twist_klines(self.klines_1m)["high"].values[-2],
                     twist_klines(self.klines_3m)["high"].values[-2],
                     twist_klines(self.klines_5m)["high"].values[-2],
                     twist_klines(self.klines_15m)["high"].values[-2],
                     twist_klines(self.klines_30m)["high"].values[-2],
                     twist_klines(self.klines_1h)["high"].values[-2]]

        nums = {"low_nums": low_nums, "high_nums": high_nums}

        self.task_list = []
        for user in self.user_list:
            if not user.task_lock:  # 添加异步任务
                self.task_list.append(user.execute(score, now_price, nums))
                user.task_lock = True

        if len(self.task_list) > 0:  # 执行异步任务
            threading.Thread(target=self.implement).start()

    def implement(self):
        asyncio.run(asyncio.wait(self.task_list))


ETCUSDT = BinanceQuantify("ETCUSDT")
APIKey = "dLMNrBArVkGSx4TdmMpTPpuWKp3MAqAOFbNvw9jCtDIX7UPHqNjhIkzh57EWOcds"
SecretKey = "p8tS9hWHrnlhVgvSSNZP4KBOrqgu8qxdNgLyCbDvNB3eNED2lUeIIApN7zYaoa3w"

ETCUSDT.user_list.append(BinanceStrategy(UID=0, APIKey=APIKey, SecretKey=SecretKey, symbol="ETCUSDT"))
while True:
    time.sleep(1)